package altanovela.hbsp.app;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import altanovela.hbsp.model.Mahasiswa;

public class MainApplication {
	SessionFactory sessionfactory = null;
	Session session = null;
	
	public void processing(){
		System.out.println(".: WELCOME TO THE APP :.");
		session = sessionfactory.openSession();
		try{
			System.out.println("inserting data...");
			insertNewData();
			System.out.println("show data...");
			showCurntData();
		}catch (Exception e) {
			e.printStackTrace();
		}
		session.close();
		System.out.println(".: APPLICATION FINISH :.");
	}	
	
	// MAIN FUNCTION
	public void insertNewData() throws Exception{
		Mahasiswa newmhs = new Mahasiswa();
		newmhs.setIdmhs(generateNewId("IDMHS"));
		newmhs.setNama("Won Bin");
		newmhs.setJurusan("Akting");
		newmhs.setGender("L");		
		session.beginTransaction();
		session.save(newmhs);
		session.getTransaction().commit();
	}
	@SuppressWarnings("unchecked")
	public void showCurntData() throws Exception{
		Query query = null;
		List<Mahasiswa> result = null;
//		query = session.createQuery(
//				"from " +
//				"	Mahasiswa " +
//				"where " +
//				"	nilai_a > 50" +
//				"order by id asc"
//				);
		query  = session.createQuery("from Mahasiswa");
		result = query.list();
		if(result!=null){
			for (Mahasiswa mhs : result) {
				System.out.println(
						mhs.getIdmhs()  +" "+
						mhs.getNama()   +" "+
						mhs.getJurusan()+" "+
						mhs.getGender());
			}
		}
	}
	
	// MISC FUNCTION
	public long getLongID(String stringid){
		return Long.valueOf(stringid.substring(5));
	}	
	@SuppressWarnings("unchecked")
	public String generateNewId(String prfix){
		Query query = session.createQuery(
					"select idmhs from Mahasiswa");
		List<String> result = query.list();
		int idx = 0;
		if(result!=null && result.size() > 0){
			for (int i=0; i<result.size(); i++){
				if(getLongID(result.get(idx)) < 
				   getLongID(result.get(i)))
				   idx = i;
			}
			return prfix+(getLongID(result.get(idx))+1);
		}else{
			return prfix+"0"; 
		}
	}
	
	// SETTER AND GETTER
	public SessionFactory getSessionfactory() {
		return sessionfactory;
	}
	public void setSessionfactory(SessionFactory sessionfactory) {
		this.sessionfactory = sessionfactory;
	}
}
